#!/usr/bin/env bash

# Copyright (c) 2011 Cloudera, Inc. All rights reserved.

set -e
set -x

# Explicitly add RHEL5/6, SLES11/12 locations to path
export PATH=/usr/kerberos/bin:/usr/kerberos/sbin:/usr/lib/mit/sbin:/usr/sbin:/usr/lib/mit/bin:/usr/bin:$PATH

CMF_REALM=TDDATA.COM
CMF_PRINCIPAL=admin/admin
CMF_KEYTAB_FILE=/opt/td-data/kerberos-manage/keytabs/admin.keytab

KEYTAB_OUT=$1
PRINC=$2
MAX_RENEW_LIFE=$3

KADMIN="kadmin -k -t $CMF_KEYTAB_FILE -p $CMF_PRINCIPAL -r $CMF_REALM"

RENEW_ARG=""
if [ $MAX_RENEW_LIFE -gt 0 ]; then
  RENEW_ARG="-maxrenewlife \"$MAX_RENEW_LIFE sec\""
fi


$KADMIN -q "addprinc $RENEW_ARG -randkey $PRINC"

if [ $MAX_RENEW_LIFE -gt 0 ]; then
  RENEW_LIFETIME=`$KADMIN -q "getprinc -terse $PRINC" | tail -1 | cut -f 12`
  if [ $RENEW_LIFETIME -eq 0 ]; then
    echo "Unable to set maxrenewlife"
    exit 1
  fi
fi

$KADMIN -q "xst -k $KEYTAB_OUT $PRINC"
chmod 600 $KEYTAB_OUT
